<template>
  <div style="">
    <Header :left="true" leftText="返回" title="加严填报审批"> </Header>
    <NoticeBar color="#1989fa" background="#ecf9ff" style="margin-top: 5px; font-size: 15px; font-weight: bold"
      left-icon="description">基本信息</NoticeBar>
    <van-form :style="autoHeight" @submit="onSubmit">
      <van-field readonly class="formstyle" style="font-weight: bold" :value="item.FromDatetime" label="加严开始时间"
        placeholder="加严开始时间" show-word-limit rows="2" autosize />

      <van-field class="formstyle" readonly :value="item.PLineID" name="生产线" label="生产线" />

      <van-field readonly class="formstyle" :value="showAddStrictTypeName(item.StrictTypeID)" name="加严原因" label="加严类型" />


      <van-field readonly required class="formstyle" name="生产订单" label="生产订单" :value="showPOrderIDName(item.POrderID)"
        show-word-limit rows="2" autosize />



      <van-field class="formstyle" rows="4" autosize type="textarea" maxlength="100" :value="item.StrictDescription"
        name="加严说明" label="加严说明" placeholder="加严说明" readonly />

      <van-field class="formstyle" rows="4" autosize maxlength="100" :value="item.AppearanceCheckRecord" name="外观检验记录"
        label="外观检验记录" placeholder="外观检验记录" readonly />


      <NoticeBar color="#1989fa" background="#ecf9ff" style="margin-top: 5px; font-size: 15px; font-weight: bold"
        left-icon="description">审核意见</NoticeBar>

      <van-field label="审批" required class="formstyle">
        <template #input>
          <van-radio-group v-model="item.ProcessAgree" direction="horizontal" :disabled="lock">
            <van-radio :name="true">同意</van-radio>
            <van-radio :name="false">不同意</van-radio>
          </van-radio-group>
        </template>
      </van-field>

      <van-field required class="formstyle" rows="4" autosize type="textarea" maxlength="100" :readonly="lock"
        :rules="[{ required: true, message: '审核意见不能为空' }]" v-model="item.ProcessMemo" name="审核意见" label="审核意见" />


      <div style="margin: 16px" v-if="!lock">
        <van-button color="#138087" round block type="info" native-type="submit">保存</van-button>
      </div>
    </van-form>
    <!-- <div style="margin: 16px"
      v-if="item.AppearanceCheckRecord != 0 && item.AppearanceCheckRecord != '' && item.AppearanceCheckRecord != null">
      <van-button color="" round block type="info" @click="getRecord" style="">查看外观检验不合格记录</van-button>
    </div>
    <div style="margin: 16px">
      <van-button color="#23C6C8" round block type="info" @click="checkSYS">查看实验室检验不合格项</van-button>
    </div>
    <div style="margin: 16px">
      <van-button color="#1AB394" round block type="info" @click="openQA">打开质量辅助决策界面</van-button>
    </div>
    <div style="margin: 16px">
      <van-button color="#1AB394" round block type="info" @click="CheckTM">查看实验室复测记录</van-button>
    </div> -->
    <van-row gutter="20">
        <van-col span="12">
          <div style="margin: 16px">
            <van-button color="#008792" round block type="info" @click="getRecord(form.AppearanceCheckRecord1)"
              style="">查看外观检验不合格记录</van-button>
          </div>
        </van-col>
        <van-col span="12">
          <div style="margin: 16px">
            <van-button color="#33a3dc" round block type="info" @click="checkSYS">查看实验室检验不合格项</van-button>
          </div>
        </van-col>
      </van-row>

      <van-row gutter="20">
        <van-col span="12">
          <div style="margin: 16px">
            <van-button color="#1AB394" round block type="info" @click="openQA">打开质量辅助决策界面</van-button>
          </div>
        </van-col>
        <van-col span="12">
          <div style="margin: 16px">
            <van-button color="#005831" round block type="info" @click="CheckTM">查看实验室复测记录</van-button>
          </div>
        </van-col>
      </van-row>
  </div>
</template>

<script>
import {
  Col,
  Row,
  Form,
  Cell,
  Icon,
  Field,
  tab,
  tabs,
  NumberKeyboard,
  Image as VanImage,
  Picker,
  popup,
  SubmitBar,
  Button,
  Loading,
  Overlay,
  Dialog,
  Toast,
  NoticeBar,
  Tag,
  DatetimePicker,
  ImagePreview,
  CellGroup,
  Uploader,
  Cascader,
  Calendar,
  RadioGroup,
  Radio,
  Divider,
  Stepper,
  AddressList,
  Checkbox,
  CheckboxGroup,
} from "vant";

import "vue-easytable/libs/themes-base/index.css";
import { VTable } from "vue-easytable";
import { _httpClient } from "@/libs/apisie";
import { _httpClient as _httpClientApi } from "@/libs/api";
import { _httpClient as _httpClientApisie } from "@/libs/apisie";
import { getToken, getBaseApiFrefix } from "@/libs/auth";
import Header from "@/components/header.vue";
import { storage } from "@/libs/utils";

Vue.use(Form);
Vue.use(Field);
Vue.use(Overlay);
Vue.use(Loading);
Vue.use(Picker);
Vue.use(popup);
Vue.use(SubmitBar);
Vue.use(VanImage);
Vue.use(DatetimePicker);
Vue.use(Cascader);
Vue.use(Calendar);
Vue.use(Cell);
Vue.use(RadioGroup);
Vue.use(Radio);
Vue.use(Divider);
Vue.use(Stepper);
Vue.use(Button);
Vue.use(AddressList);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Col);
Vue.use(Row);
Vue.use(tab);
Vue.use(tabs);

export default {
  name: 'tightaudit',
  components: {
    Form,
    Row,
    Col,
    Button,
    Header,
    Form,
    Cell,
    Icon,
    Field,
    NumberKeyboard,
    Dialog,
    Toast,
    NoticeBar,
    Row,
    Tag,
    popup,
    DatetimePicker,
    ImagePreview,
    CellGroup,
    Uploader,
    Col,
    Calendar,
    Cascader,
    Picker,
    RadioGroup,
    Radio,
    Divider,
    Stepper,
    VTable,
    AddressList,
    Checkbox,
    CheckboxGroup,
    tab,
    tabs,
  },
  data() {
    return {
      yj: "",
      showAppearanceCheckRecord: "",
      user: null,
      item: null,
      columnsStrictTypeID: [
        { StrictTypeID: "SM01", StrictTypeName: "关键工艺参数异常加严" },
        { StrictTypeID: "SM02", StrictTypeName: "机器设备异常加严" },
        { StrictTypeID: "SM03", StrictTypeName: "质量异常加严" },
        { StrictTypeID: "SM04", StrictTypeName: "生产条件异常加严" },
      ],
      columnsPOrderID: [],
      lock: false,

    };
  },
  created() {
    this.user = JSON.parse(storage.get("user"));
    this.user.userId = this.user.userName;
  },

  mounted() {
    this.id = this.$ac.pageParam.id
    this.lock = this.$ac.pageParam.lock
    this.getPOrderID()
    this.getDetail(this.id)


  },
  watch: {
    "item.ProcessAgree": {
      handler(newVal, oldavl) {
        if (this.lock) {
          return
        }
        if (newVal == true) {
          this.item.ProcessMemo = this.formatDate(new Date()) + " " + this.user.employeeName + "已审核加严管控，同意加严"
        } else {
          this.item.ProcessMemo = this.formatDate(new Date()) + " " + this.user.employeeName + "已审核加严管控，不同意加严"
        }

      },
      immediate: true
    },

  },

  methods: {
    // 获取当前时间 yy-mm-dd
    formatDate(date) {


      let year = date.getFullYear()
      let mouth = date.getMonth() + 1
      if (mouth < 10) {
        mouth = '0' + mouth
      }
      let day = date.getDate()
      if (day < 10) {
        day = '0' + day
      }

      var h = date.getHours();
      h = h < 10 ? '0' + h : h;
      var m = date.getMinutes();
      m = m < 10 ? '0' + m : m;
      return year + '-' + mouth + '-' + day + " " + h + ":" + m
    },
    openQA() {
      let _this = this
      api.openWin({
        name: 'qAssistance',
        url: './qAssistance-qualityAssistance.html',
        pageParam: {
          POrderID: _this.item.POrderID,
          PlineID: _this.item.PLineID
        }

      });


    },
    getRecord() {

      let id = this.item.AppearanceCheckRecord

      api.openWin({
        name: 'qCcheckReview',
        url: './quality-qCcheckReview.html',
        pageParam: {
          id: id
        }
      });

    },
    async getDetail(id) {
      try {

        let rest = await _httpClientApisie.get(
          _httpClientApisie.getApiPrefix() +
          "/AddStrictManage/GetEntity?id=" + id
        )


        if (rest.HttpCode === "200") {
          this.item = rest.Data
          //LevelFilled
          this.yj = this.item.ProcessMemo


          if (!this.lock) {
            this.item.ProcessAgree = true
          }
        }

      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }

    },
    showAddStrictTypeName(AddStrictType) {
      var AddStrictTypeName = AddStrictType;
      this.columnsStrictTypeID.forEach((item) => {
        if (item.StrictTypeID === AddStrictType) {
          AddStrictTypeName = item.StrictTypeName;
        }
      });
      return AddStrictTypeName;
    },
    showPOrderIDName(POrderID) {
      var POrderIDName = POrderID;
      this.columnsPOrderID.forEach((item) => {
        if (item.POrderID === POrderID) {
          POrderIDName = item.POrderIDAndMaterialName;
        }
      });
      return POrderIDName;
    },

    async getPOrderID() {
      let _this = this;
      try {
        let res = await _httpClient.get(
          _httpClient.getApiPrefix() + "/ProductionOrder/GetList"
        );
        if (res.HttpCode === "200") {
          let teamMap = res.Data.map((item) => ({
            POrderID: item.POrderID,
            MaterialName: item.MaterialName,
            MaterialID: item.MaterialID,
            POrderIDAndMaterialName: item.POrderID + " " + item.MaterialName,
          }));
          _this.columnsPOrderID = teamMap;
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },

    async checkSYS() {
      let id = this.form.LaboratoryCheckRecord
      if (id == "" || id == null || id == undefined) {
        Toast.clear()
        Toast.fail("当前没有维护实验室检验记录，无法获取不合格记录！")
        return
      }

      api.openWin({
        name: 'viewlaboratorytest',
        url: './equipmentsj-viewlaboratorytest.html',
        pageParam: {
          id: id
        }
      });
    },
    async CheckTM() {
      let id = this.form.LaboratoryCheckRecord
      if (id == "" || id == null || id == undefined) {
        Toast.clear()
        Toast.fail("当前没有维护实验室复测记录，无法获取复测记录！")
        return
      }

      api.openWin({
        name: 'viewlaboratorytest1',
        url: './equipmentsj-viewlaboratorytest1.html',
        pageParam: {
          id: id
        }
      });
    },

    async onSubmit() {
      var _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "请稍等...",
      });

      try {

        this.item.ProcessManName = this.user.userName
        this.item.ProcessMan = this.user.userName;
        this.item.Processed = true
        this.item.ProcessDatetime = new Date()


        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/AddStrictManage/SaveEntity",
          {
            body: this.item
          }
        );

        if (res.Message != null) {
          //message不为空,有报错信息，打卡失败 暂时这样判断
          Toast.clear();
          Toast.fail("保存失败,请核对信息！");
        } else {
          //打卡成功
          this.sendmessage(this.item.Id)
          Toast.clear();
          Toast.success("保存成功！");
          this.$ac.sendEvent({ name: "tightaudit" })
          setTimeout(function () {
            _this.$ac.closeWin();
          }, 2000);
        }
      } catch (e) {

      }
    },

    getNowTimeplus() {
      let dateTime
      let yy = new Date().getFullYear()
      let mm = new Date().getMonth() + 1
      let dd = new Date().getDate()
      let hh = new Date().getHours()
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes()
        :
        new Date().getMinutes()
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds()
        :
        new Date().getSeconds()
      dateTime = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
      return dateTime
    },

    async sendmessage(id) {
      let _this = this;

      let eventDescription = "";
      let eventDatetime = _this.getNowTimeplus();
      let eventTypeID = "N3";
      let eventID = "";
      let messageContent = "";
      let msgContentTypeID = "";
      let pLineID = _this.item.PLineID;
      let machineID = "";
      let pShiftID = "";
      let teamID = "";
      let pOrderID = "";
      let productionBarcode = "";
      let materialBarcode = "";
      let relatedEmployee = "";
      let messageStatus = "";
      let processBatchID = "";
      let beginDatetime = _this.getNowTimeplus();
      let sendFinished = false;
      let closed = false;


      msgContentTypeID = "ADS03";
      eventID = "ADS03";
      eventDescription = "加严管控记录:" + id + "已被品管审核，同意加严！";
      messageContent = "加严管控记录:" + id + "已被品管审核，同意加严！";


      let bodysss = {
        eventDescription: eventDescription,
        eventDatetime: eventDatetime,
        eventTypeID: eventTypeID,
        eventID: eventID,
        messageContent: messageContent,
        msgContentTypeID: msgContentTypeID,
        factoryID: "TC00",
        pLineID: pLineID,
        machineID: machineID,
        pShiftID: pShiftID,
        teamID: teamID,
        pOrderID: pOrderID,
        productionBarcode: productionBarcode,
        materialBarcode: materialBarcode,
        relatedEmployee: relatedEmployee,
        messageStatus: messageStatus,
        processBatchID: processBatchID,
        beginDatetime: beginDatetime,
        sendFinished: sendFinished,
        closed: closed
      };
      try {
        let res = await _httpClientApisie.post(
          _httpClientApisie.getApiPrefix() + "/RealtimeEventMessage/SaveEntity",
          {
            body: bodysss,
          }
        );
        //alert(JSON.stringify(res));
        if (res.Message == null) {
          Toast.clear();
          Toast.success("发送成功");

        } else {
          Toast.clear();
          Toast.fail("发送失败");
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },


  },
};
</script>

<style lang="scss" scoped></style>